<?php

namespace app\api\logic;

use app\common\basic\BaseLogic;
use app\common\model\CrmCustomers;
use app\common\model\CrmFollowUps;
use support\Db;

class IndexLogic extends BaseLogic
{
    /**
     * 获取客户统计信息
     * @param int $userId
     * @return array
     */
    public function getCustomerStats(int $userId): array
    {
        // 获取当前日期
        $today = date('Y-m-d');
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $thisMonth = date('Y-m');
        $lastMonth = date('Y-m', strtotime('-1 month'));

        // 基础查询：只统计相关客户的
        $baseQuery = function ($query) use ($userId) {
            $query->where(function ($q) use ($userId) {
                $q->where('owner_id', $userId)
                  ->whereOr('creator_id', $userId);
            });
        };

        // 今日新增客户数
        $todayNew = CrmCustomers::where($baseQuery)
            ->whereDate('create_time', $today)
            ->count();

        // 昨日新增客户数
        $yesterdayNew = CrmCustomers::where($baseQuery)
            ->whereDate('create_time', $yesterday)
            ->count();

        // 本月新增客户数
        $thisMonthNew = CrmCustomers::where($baseQuery)
            ->whereMonth('create_time', $thisMonth)
            ->count();

        // 上月新增客户数
        $lastMonthNew = CrmCustomers::where($baseQuery)
            ->whereMonth('create_time', $lastMonth)
            ->count();

        // 总客户数
        $totalCustomers = CrmCustomers::where($baseQuery)->count();

        // 跟进客户数（最近7天有跟进记录的客户）
        $recentFollowCustomers = CrmFollowUps::where('operator_id', $userId)
            ->where('create_time', '>=', date('Y-m-d H:i:s', strtotime('-7 days')))
            ->distinct(true)
            ->column('customer_id');
        $followedCount = count($recentFollowCustomers);

        // 签约客户数
        $signedCount = CrmCustomers::where($baseQuery)
            ->where('status', 3)
            ->count();

        // 待跟进客户数（7天未跟进且状态为潜在客户或意向客户）
        $pendingFollowCount = CrmCustomers::where($baseQuery)
            ->whereIn('status', [1, 2])
            ->where('last_follow_time', '<', date('Y-m-d H:i:s', strtotime('-7 days')))
            ->count();

        // 客户状态分布
        $statusDistribution = CrmCustomers::where($baseQuery)
            ->field('status, count(*) as count')
            ->group('status')
            ->select()
            ->toArray();

        // 客户级别分布
        $levelDistribution = CrmCustomers::where($baseQuery)
            ->field('level, count(*) as count')
            ->group('level')
            ->select()
            ->toArray();

        // 最近7天新增客户趋势
        $weekTrend = [];
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $count = CrmCustomers::where($baseQuery)
                ->whereDate('create_time', $date)
                ->count();
            $weekTrend[] = [
                'date' => $date,
                'count' => $count
            ];
        }

        return [
            'overview' => [
                'total_customers' => $totalCustomers,
                'today_new' => $todayNew,
                'yesterday_new' => $yesterdayNew,
                'this_month_new' => $thisMonthNew,
                'last_month_new' => $lastMonthNew,
                'followed_count' => $followedCount,
                'signed_count' => $signedCount,
                'pending_follow_count' => $pendingFollowCount
            ],
            'status_distribution' => $statusDistribution,
            'level_distribution' => $levelDistribution,
            'week_trend' => $weekTrend
        ];
    }

    /**
     * 获取待跟进客户列表
     * @param int $userId
     * @param int $limit
     * @return array
     */
    public function getPendingFollowCustomers(int $userId, int $limit = 10): array
    {
        return CrmCustomers::with(['owner'])
            ->where(function ($query) use ($userId) {
                $query->where('owner_id', $userId)
                      ->whereOr('creator_id', $userId);
            })
            ->whereIn('status', [1, 2])
            ->where('last_follow_time', '<', date('Y-m-d H:i:s', strtotime('-7 days')))
            ->order('last_follow_time', 'asc')
            ->limit($limit)
            ->select()
            ->toArray();
    }

    /**
     * 获取最近跟进记录
     * @param int $userId
     * @param int $limit
     * @return array
     */
    public function getRecentFollowUps(int $userId, int $limit = 10): array
    {
        return CrmFollowUps::with(['customer', 'operator'])
            ->where('operator_id', $userId)
            ->order('create_time', 'desc')
            ->limit($limit)
            ->select()
            ->toArray();
    }
}